﻿#ifndef TCPSERVERTEST_H
#define TCPSERVERTEST_H

#include <QObject>
#include <QThread>
#include <QTimerEvent>

#include <net/tcpserver.h>

#include <net/netreading.h>
#include <net/tcpsession.h>
QNET_USING_NAMESPACE

/**
 * @brief The TcpServerTest class 表示tcp服务端测试类。
 */
class TcpServerTest : public QObject,
        public ISessionListener
{
    Q_OBJECT
    /**
     * @brief The Reading class 表示Tcp读取类。
     */
    class Reading: public NetReading
    {

    public:
        Reading(TcpSession *ownerSession, TcpServerTest *ownerTest);
        // TcpReading interface
    public:
        void onProc(const QByteArray &arry) override;
    private:
        TcpSession *m_ownerSession;
        TcpServerTest *m_ownerTest;
    };

public:
    explicit TcpServerTest(QObject *parent = nullptr);
    ~TcpServerTest() override;

    /**
     * @brief start 启动服务端。
     * @param localAddress
     * @param port
     * @return
     */
    bool start(QHostAddress localAddress, int port);
    /**
     * @brief stop 停止服务端。
     */
    void stop();
signals:
    /**
     * @brief log_signal  消息的信号。
     * @param msg 消息内容。
     */
    void log_signal(QString msg);
    // ISessionListener interface
public:
    void onError(QAbstractSocket::SocketError error) override;
    void onStateChanged(TcpSession *session, bool connected) override;
    // QObject interface
protected:
    void timerEvent(QTimerEvent *event) override;
public slots:
    /**
     * @brief fulfil 写入反馈。
     * @param sender
     * @param size
     */
    void fulfil(QSharedPointer<NetWriting> sender, int size);
private:
signals:
    void stop_signal();
private slots:
    void stop_slot();
private:
    TcpServer *m_server;
    QThread *m_thread;

    int m_timerID;
    QAtomicInt m_counter; // 数据写入计数器。

};

#endif // TCPSERVERTEST_H
